package cn.zhejianglao.shirotemplate.common.validator;

import cn.zhejianglao.shirotemplate.exception.BusinessException;
import cn.zhejianglao.shirotemplate.exception.ExceptionCode;
import lombok.extern.slf4j.Slf4j;
import net.sf.oval.ConstraintViolation;
import net.sf.oval.Validator;

import java.util.List;
import java.util.stream.Collectors;

/**
 * validate parameters
 */

@Slf4j
public class ParamValidator {

    public static void validate(Object param, int exceptionCode, String exceptionMessage) {
        Validator validator = new Validator();
        List<ConstraintViolation> violationList = validator.validate(param);
        if (violationList.isEmpty()) {
            log.info("all passes");
            return;
        }

        List<String> errorList = violationList
                .stream()
                .map(ConstraintViolation::getMessage)
                .collect(Collectors.toList());
        log.info("illegal parameter(s)：{}", errorList);
        throw new BusinessException(exceptionCode, exceptionMessage + errorList);
    }

    public static void validate(Object param) {
        validate(param, ExceptionCode.Param.ILLEGAL_PARAM_CODE, ExceptionCode.Param.ILLEGAL_PARAM_MSG);
    }

}
